from django.shortcuts import render
from django.views import View
from apps.location.models import Area
from django.http import JsonResponse
from django.core.cache import cache
# Create your views here.
class AreaView(View):

    def get(self,request):
        province_dict=cache.get('province') #cache是缓存工具
        #先判断缓存
        if province_dict is None:

        # 省数据：查询省份获得列表，遍历列表，转换为字典，返回
            provinces=Area.objects.filter(parent__isnull=True)

            province_dict=[]
            for item in provinces:
                province_dict.append({
                    'id':item.id,
                    'name':item.name

                })
            cache.set('province',province_dict)
        return JsonResponse({'code':0,'errmsg':'done','province_list':province_dict})


class SubsAreaView(View):

    #有parent_id获取下一级市区县数据
    def get(self,request,parent_id):
        #两个方法
        # subs=Area.objects.filter(parent=parent_id)

        #或
        # parent_area=Area.objects.get(id=parent_id)
        # parent_area.subs.all()
#获取parent_id的area数据，获取下一级数据，遍历下一级，组织返回
        #先读取缓存
        sub_data=cache.get('sub_data_%s'%parent_id)
        if sub_data is None:
            parent_area=Area.objects.gets(id=parent_id)
            subs=parent_area.subs.all() #all()查询获取指向数据

            sub_list=[]
            for item in subs:
                sub_list.append({
                    'id':item.id,
                    'name':item.name
                })

            sub_data={
                'id':parent_area.id,
                'name':parent_area.name,
                'subs':sub_list
            }
            cache.set('sub_data_%s'%parent_id,sub_data)
        return JsonResponse({'code':0,'sub_data':sub_data})




